<template>
  <div class="box">
    <div class="box-content" v-if="curPage==='loginPage'">
      <div class="login-title">
        {{isFirst ? '登录' : '绑定手机号'}}
      </div>
      <div class="login-tabs" v-if="isShowTabs">
        <div
          class="login-tab"
          :class="{ active: active === 'password' }"
          @click="tabSwitch('password')"
        >
          用户名
        </div>
        <div
          class="login-tab"
          :class="{ active: active === 'verification' }"
          @click="tabSwitch('verification')"
        >
          手机号
        </div>
      </div>
      <div class="login-user" v-if="isShowUser">
        <div class="login-input-row">
          <div class="login-label">用户名</div>
          <div class="login-input">
            <input
              class="login-inp"
              name="account"
              ref="userInp"
              v-validate="'required'"
              v-model="form.account" 
              type="text"
              @keyup.enter="goHome"
              @keydown="keyDown($event)"
            />
          </div>
          <div v-show="errors.has('account')" class="el-form-item__error">
            {{ errors.first("account") }}
          </div>
        </div>
        <div class="login-input-row">
          <div class="login-label">密码</div>
          <div class="login-input">
            <input
              name="password"
              v-validate="'required'"
              v-model="form.password"
              class="login-inp"
              type="password"
              @keyup.enter="goHome"
              @keydown="keyDown($event)"
            />
          </div>
          <div v-show="errors.has('password')" class="el-form-item__error">
            {{ errors.first("password") }}
          </div>
        </div>
        <div class="login-check-row">
          <label class="check-label">
            <input
              type="checkbox"
              v-model="checkbox"
              value="下次自动登录"
            />
            下次自动登录
          </label>
          <div class="forget-txt" @click="toForgetPassword">忘记密码</div>
        </div>
        <div class="step-btns">
          <div class="step-btn active" @click="goHome">登录</div>
        </div>
        <div class="login-line">
          <div class="line">或者</div>
        </div>
        <div class="login-button">暂未开放</div>
      </div>

      <div class="phone">
        <div class="phone-content" v-if="isShowPhone">
          <div class="login-input-row">
            <div class="login-label">手机号</div>
            <div class="login-input">
              <input
                class="login-inp"
                name="phone"
                ref="phoneInp"
                v-validate="'required|phone'"
                v-model="phoneNums" 
                type="text"
                :maxlength="11"
                @keyup.enter="continuePhone"
                @keydown="keyDown($event)"
              />
            </div>
            <div v-show="errors.has('phone')" class="el-form-item__error">
              {{ errors.first("phone") }}
            </div>
          </div>
          <div class="phone-btns">
            <div @click="continuePhone" class="phone-btn active">继续</div>
          </div>

          <other-way />
        </div>
      </div>
    </div>

    <div v-if="vcShow">
      <Vcode :show="vcShow" @success="vcSuccess"/>
    </div>
    

    <!-- 忘记密码 -->

    <reset
      v-if="curPage==='resetPage'"
      @toLogin="toLogin"
      @goBackLogin="goBackLogin"
    ></reset>

    <sms
      v-if="curPage==='smsPage'"
      :phoneNums="phoneNums"
      :isBindPhone="isHasPhone"
      :lastNumber="lastPhoneNumber"
      @continuePhoneSendCode="continuePhoneSendCode"
      @continueLast="continueLast"
      @goBackPhone="goBackPhone"
    >
    </sms>


  </div>
</template>

<script>
import Cookies from "js-cookie";
import * as api from "@/api";
import { BaseURL } from "@/consts/consts";
import Vcode from "vue-puzzle-vcode"
export default {
  components: {
    Vcode
  },
  data() {
    return {
      curPage: 'loginPage',
      active: "password",
      isFirst: true,
      isShowTabs: true,
      isShowUser: true,
      isShowPhone: false,
      form: {
        account: "",
        password: "",
      },
      phoneNums: '',
      isHasPhone: 1,
      lastPhoneNumber: "",
      verifyData: {},
      checkbox: false,
      vcShow: false,
    };
  },
  watch: {
    isShowUser(val) {
      if (val) {
        setTimeout(() => {
          this.$refs.userInp.focus()
        }, 800)
      }
    },
    isShowPhone(val) {
      if (val) {
        setTimeout(() => {
          this.$refs.phoneInp.focus()
        }, 800)
      }
    }
  },
  methods: {
    keyDown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false
      }
    },

    //读取cookie
    getCookie() {
      this.form.account = Cookies.get('account') || ''
      this.form.password = Cookies.get('password') || ''

      // 如果勾选了下次自动登录，那就直接登进去
      let password = localStorage.getItem('password') || ''
      if (password) {
        this.form = {
          account: localStorage.getItem('username'),
          password
        }
        this.login()
      }
    },

    tabSwitch(key) {
      this.active = key;
      this.isShowUser = this.active === "password";
      this.isShowPhone = this.active === "verification";
    },

    vcSuccess() {
      this.vcShow = false
      // this.form =  {
      //   account: "",
      //   password: "",
      // }
    },

    toForgetPassword() {
      this.curPage = 'resetPage'
    },

    goHome() {
      this.$validator.validateAll().then((valid) => {
        if (valid) {
          this.login();
        }
      });
    },
    continuePhone() {
      // 0 绑定手机号
      let phone = this.phoneNums
      console.log('号码啊: ', phone)
      if (phone && phone.length === 11 && /^1[3-9]\d{9}$/.test(phone)) {
        this.lastPhoneNumber = phone.substr(phone.length - 4);
        this.phoneCheck()
        
        
      } else if (phone === '') {
        this.$message.warning("手机号不能为空");
        return false;
      } else {
        this.$message.warning("请输入正确的手机号");
        return false;
      }
    },
    toHome(data) {
      this.$message.success("登录成功");
      this.setStorage(data)
      
      this.$store.commit("handleUserRole", data.role_name); // 角色
      this.$store.commit("handleAltered", data.altered);
      let permission = JSON.parse(data.permission);
      if (this.$store.state.user_role === "超级管理员") {
        for (let i in JSON.parse(data.permission)) {
          this.$set(permission[i], "addChecked", true);
          this.$set(permission[i], "editChecked", true);
          this.$set(permission[i], "deletChecked", true);
        }
        localStorage.setItem("permission", JSON.stringify(permission));
      } else {
        localStorage.setItem("permission", data.permission);
      }
      this.nextAutoLogin()
      permission.some(p => {
        if (p.checked) {
          sessionStorage.setItem("currentMenu", p.index)
          this.$router.push(p.path)
          return p.checked
        }
      })
      
    },
    continuePhoneSendCode(flag) {

    },
    //手机的登录  进入首页
    continueLast(data) {
      // 有组织id就是说明是组织账号，直接跳中控
      if (data.organization_id) {
        for (let k in data) {
          Cookies.set(k, data[k]);
        }
        if (process.env.VUE_APP_ENV === "development") {
          window.location.href = `http://localhost:6500/control`;
        } else {
          window.location.href = `${BaseURL}/control`;
        }
      } else {
        this.$router.push("/org");
      }
    },

    // 返回上一级
    goBackPhone(flag) {
      this.curPage = 'loginPage'
      this.active = "verification";
    },

    setStorage(data) {
      localStorage.setItem("access_token", data.access_token);
      localStorage.setItem("refresh_token", data.refresh_token);
      localStorage.setItem("username", data.name);
      localStorage.setItem("organization_id", data.organization_id);
      localStorage.setItem("user_id", data.user_id);
    },

    jump(data) {
      // 有手机号有组织id就是说明是组织账号，直接跳中控
      if (data.organization_id) {
        for (let k in data) {
          Cookies.set(k, data[k]);
        }
        this.nextAutoLogin()
        if (process.env.VUE_APP_ENV === "development") {
          window.location.href = `http://localhost:6500/control`;
        } else {
          const { protocol, host } = window.location
          window.location.href = `${protocol}//${host}/control`;
        }
      } else {
        this.toHome(data);
      }

      
    },

    nextAutoLogin() {
      if (this.checkbox) {
        let {account:userName, password} = this.form
        Cookies.set(userName, password, { expires: 7 })
        localStorage.setItem('password', password)
        localStorage.setItem('username', userName)
      }
    },

    
    // 检查手机号是否存在
    async phoneCheck() {
      let params = {
        phone: this.phoneNums,
        type: this.isHasPhone
      }

      const { code, data, message } = await api.login(this).phoneCheck(params);
      if (code === 0) {
        this.loginSmsVerifyCode()
      }
    },

    async login() {
      const { code, data, message } = await api.login(this).login(this.form);
      if (code === 0) {
        // 0---否  1 ---有手机号
        this.isHasPhone = data.has_phone;
        if (this.isHasPhone == 0) {
          this.$confirm("请先绑定手机号", {
            confirmButtonText: "确定",
            type: "warning",
            showClose: false,
            showCancelButton: false,
          })
            .then(() => {
              this.phoneNums = ''
              this.isFirst = false;
              this.isShowTabs = false;
              this.isShowUser = false;
              this.isShowPhone = true;
              console.log('没有手机号时候的d: ', data)
              for (let k in data) {
                Cookies.set(k, data[k])
              }
              this.setStorage(data)
            })
        } else {
          this.jump(data)
        }
      } else {
        console.log('登录不成！：', code)
        this.vcShow = true
        // this.$message.error(message)
        // this.active = "verification"
        // this.isShowUser = false
        // this.isShowPhone = true
      }
    },

    // 手机发送短信验证码
    async loginSmsVerifyCode() {
      let params = {};
      params.phone = this.phoneNums
      const { code, data, message } = await api.login(this).smsVerifyCode(params);
      if (code === 0) {
        this.curPage = 'smsPage'
        console.log('发完验证码后d: ', data)

        if (this.isHasPhone === 1) {
          // localStorage.setItem("access_token", data.access_token);
          
        }

      }
    },


    // 退回登录页面
    toLogin(data) {
      this.resetPassword = data.password;
      this.user_id = data.user_id;
      this.curPage = 'loginPage'
      this.isShowUser = true;
    },

    goBackLogin(flag) {
      this.curPage = 'loginPage'

      this.isShowUser = true;
    },
  },
  created() {
    this.getCookie();
  },
  mounted() {
    if (this.isShowUser) {
      setTimeout(() => {
        if (!this.form.account) {
          this.$refs.userInp.focus()
        }
      }, 2000)
    }
  }
  
};
</script>

<style>
</style>